    //
//  ProductList.m
//  smartInfo
//
//  Created by Sanjay Singh on 05/11/11.
//  Copyright 2011 Dhakera. All rights reserved.
//

#import "ProductList.h"
#define kInAppPurchaseProUpgradeProductId @"50"

@implementation ProductList
@synthesize productId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    [activity release];
    [tbl_productList release];
    [ [SKPaymentQueue defaultQueue] removeTransactionObserver: self];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title =@"Select Subscription";
    
    tbl_productList =[[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 468.0) style:UITableViewStyleGrouped];
	//tbl_productList.backgroundColor = nil;
	//tbl_productList.backgroundColor = [UIColor colorWithRed:0.691 green:0.089 blue:0.121 alpha:1];
    [self.view addSubview:tbl_productList];
    tbl_productList.delegate=self;
    tbl_productList.dataSource=self;
    
    //set Indicater
    activity =[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activity.frame=CGRectMake(330, 300, 60, 60);
	
	
    [self.view addSubview:activity];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	if (indexPath.section ==0)
    {
        cell.textLabel.text =@"Subscribe 50 Emails for 12.99 GBP";
		cell.textLabel.font = [UIFont systemFontOfSize:16];
    }
    else
        if (indexPath.section ==1)
        {
            cell.textLabel.text =@"Subscribe 100 Emails for 24.99 GBP";
			cell.textLabel.font = [UIFont systemFontOfSize:16];
        }
	
    
    
    // Configure the cell...
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section ==0)
    {
        productId =@"1299";//501
		int_NoOfEmail = 50;
    }
    else
        if (indexPath.section ==1)
        {
            productId =@"2499";//505
			int_NoOfEmail = 100;
        }
        
	
               
    [tableView deselectRowAtIndexPath:indexPath animated:YES ];
    [self loadStore];
    
  //  if ([self canMakePurchases])

        [self purchaseProUpgrade:productId];
    
    
    [activity startAnimating];
    self.view.userInteractionEnabled=FALSE;
    self.view.alpha =0.7;
    [self.navigationItem setHidesBackButton:YES animated:YES];
}


#pragma -
#pragma Public methods

//
// call this method once on startup
//
- (void)loadStore
{
    // restarts any purchases if they were interrupted last time the app was open
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    // get the product description (defined in early sections)
	/////// [self requestProUpgradeProductData];
}

//
// call this before making a purchase
//
- (BOOL)canMakePurchases
{
    return [SKPaymentQueue canMakePayments];
}

//
// kick off the upgrade transaction
//
- (void)purchaseProUpgrade:(NSString *)pid
{
    SKMutablePayment *payment = [SKMutablePayment paymentWithProductIdentifier:pid];
	payment.quantity = 1; /// default property is 1

	[[SKPaymentQueue defaultQueue] addPayment:payment];
    
    NSLog(@"===================PayyyyyyyyyyyyMent");
}

#pragma -
#pragma Purchase helpers

//
// saves a record of the transaction by storing the receipt to disk
//
- (void)recordTransaction:(SKPaymentTransaction *)transaction
{
    if ([transaction.payment.productIdentifier isEqualToString:kInAppPurchaseProUpgradeProductId])
    {
        // save the transaction receipt to disk
        [[NSUserDefaults standardUserDefaults] setValue:transaction.transactionReceipt forKey:@"proUpgradeTransactionReceipt" ];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    NSLog(@"=======================recordTransaction");
}

//
// enable pro features
//
- (void)provideContent:(NSString *)productId_
{
    if ([productId_ isEqualToString:kInAppPurchaseProUpgradeProductId])
    {
        // enable the pro features
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isProUpgradePurchased" ];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
	NSLog(@"=========================provideContent");
}

//
// removes the transaction from the queue and posts a notification with the transaction result
//
- (void)finishTransaction:(SKPaymentTransaction *)transaction wasSuccessful:(BOOL)wasSuccessful
{
    NSLog(@"=======================finishTransaction");
    
    // remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:transaction, @"transaction" , nil];
    if (wasSuccessful)
    {
        // send out a notification that we’ve finished the transaction
        [[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerTransactionSucceededNotification object:self userInfo:userInfo];
    }
    else
    {
        // send out a notification for the failed transaction
        [[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerTransactionFailedNotification object:self userInfo:userInfo];
    }
}

//
// called when the transaction was successful
//
- (void)completeTransaction:(SKPaymentTransaction *)transaction
{
    [self recordTransaction:transaction];
    [self provideContent:transaction.payment.productIdentifier];
    [self finishTransaction:transaction wasSuccessful:YES];
    
    NSLog(@"=================completeTransaction");
}

//
// called when a transaction has been restored and and successfully completed
//

- (void)restoreTransaction:(SKPaymentTransaction *)transaction
{
    [self recordTransaction:transaction.originalTransaction];
    [self provideContent:transaction.originalTransaction.payment.productIdentifier];
    [self finishTransaction:transaction wasSuccessful:YES];
    
    NSLog(@"=======================restoreTransaction");
}

//
// called when a transaction has failed
//
- (void)failedTransaction:(SKPaymentTransaction *)transaction
{
    NSLog(@"========================failedTransaction");
    
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        // error!
        [self finishTransaction:transaction wasSuccessful:NO];
    }
    else
    {
        // this is fine, the user just cancelled, so don’t notify
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    }
}

#pragma mark -
#pragma mark SKPaymentTransactionObserver methods

//
// called when the transaction status is updated
//
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    
	[activity stopAnimating];
    self.view.userInteractionEnabled=TRUE;
    self.view.alpha =1.0;
    [self.navigationItem setHidesBackButton:NO animated:YES];
    
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
                int remainingEmail=0;
				
                UIAlertView *alert1;
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                
                alert1 = [[UIAlertView alloc] initWithTitle:@"Subscription succesfully purchased" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
				[alert1 show];
				alert1.tag=-111;
				[alert1 release];
                
                //Add no purchased email to NSUserDefault
                remainingEmail =[[[NSUserDefaults standardUserDefaults] valueForKey:@"Email"] intValue];
                int_NoOfEmail= remainingEmail + int_NoOfEmail;
				[[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",int_NoOfEmail] forKey:@"Email"];
				//[[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"Email"];
				NSLog(@"int no of email %d",int_NoOfEmail);   
                
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                alert1 = [[UIAlertView alloc] initWithTitle:@"SKPaymentTransaction  StateFailed Try Again Later" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
				// [alert1 show];
                [alert1 release];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
                
                alert1 = [[UIAlertView alloc] initWithTitle:@"SKPaymentTransaction StateRestored Try Again Later" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
				// [alert1 show];
                [alert1 release];
                break;
            default:
                break;
        }
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (alertView.tag ==-111)
	{
        [self.navigationController popViewControllerAnimated:YES];
		
	}
}



@end